package zct.proj.customView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;

import zct.proj.pojo.EquipDC;
import zct.proj.pojo.EquipXHJ;
import zct.proj.pojo.EquipmentInfo;
import zct.proj.pojo.LogicSwitcher;
import zct.proj.pojo.StationInfo;
import zct.proj.pojo.StationSummary;
import zct.proj.pojo.Switcher;
import zct.proj.util.Const;
import zct.proj.util.DrawUtil;
import zct.proj.util.IniParser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.animation.TranslateAnimation;

public class MapDisp extends SurfaceView implements SurfaceHolder.Callback {

	SurfaceHolder sh;
	Context ctx;
	Bitmap cacheImage;
	StationSummary ss;
	ArrayList<EquipmentInfo> sbList;
	StationInfo stationInfo;
	DrawUtil drawUtil;
	
	
	
	
	
	
	
	
	
	
	
	private float beforeLenght;
    private float afterLenght;
    private boolean multiFinger = false;
   
    private int tw;
    private int th;
    
    private float x0;
    private float y0;
    
    private int w0;
    private int h0;
    private int l0;
    private int t0;
    private float xpos;
    private float ypos;
    
//    private float rx0;
//    private float ry0;
    
    private float scale;
	
//    private TranslateAnimation trans;
    
    /**
	 * 计算两点间的距离
	 */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }
    
    /**
     * 处理触碰..
     */
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{	
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
//    		mode = DRAG;
//	    	x1 = (int) event.getRawX();
//	    	y1 = (int) event.getRawY();
    		if (event.getPointerCount() >= 2) {
    			getBasePostion(event, false);
//        		Log.v("ActionDownMulti", x0 + "," + y0);
    		} else {
    			getBasePostion(event, true);
//            	Log.v("ActionDownSingle", x0 + "," + y0);
    		}
    		multiFinger = true;
//        	if(event.getPointerCount()==2)
//        		beforeLenght = spacing(event);
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
//            if (spacing(event) > 10f) {
//                    mode = ZOOM;
//            		beforeLenght = spacing(event);
//            }
        	if (event.getActionIndex() == 1 && multiFinger) {
        		getBasePostion(event, false);
        	}
//    		Log.v("PointerDown", x0 + "," + y0);
            break;
        case MotionEvent.ACTION_UP:
    		/*判断是否超出范围     并处理*/
    		int left = this.getLeft();
    		int right = this.getRight();
    		int top = this.getTop();
    		int bottom = this.getBottom();
    		int w = right - left;
    		int h = bottom - top;
    		int offX = 0;
    		int offY = 0;
    		
    		if (w < tw && h < th) {
//    			Log.v("zoom", "<<<<<<<<");
    			float zoomW = tw / w;
    			float zoomH = th / h;
    			if (zoomW < zoomH) {
    				left = 0;
    				right = tw;
    				w = tw;
    				h = (int) (zoomW * h);
//    				top = (th - zoomW * h) / 2;
    			} else {
    				top = 0;
    				bottom = th;
    				h = th;
    				w = (int) (zoomH * w);
    			}
    		}
//    		Log.v("size", this.getLeft() + "," + this.getRight() + "," + (this.getRight() - this.getLeft()) + "," + this.getWidth());
//    		Log.v("vvvv", w + "," + tw + "," + h + "," + th);
    		// 长或宽大于屏幕尺寸时，移动到边缘
    		if (w >= tw) {
    			if (left > 0) {
    				offX = -left;
    			} else if (right < tw) {
    				offX = tw - right;
    			}
    		} else {
    			offX = (tw - w) / 2 - left;
    		}
    		
    		if (h >= th) {
    			if (top > 0) {
    				offY = -top;
    			} else if (bottom < th) {
    				offY = th - bottom;
    			}
    		} else {
    			offY = (th - h) / 2 - top;
    		}
    		
//    		drawUtil.zoom(scale);
//    		drawUtil.drawControls();
    		
    		this.layout(left + offX, top + offY, right + offX, bottom + offY);
//    		trans = new TranslateAnimation(-offX, 0, -offY, 0);
//    		trans.setDuration(5000);
//    		this.setAnimation(trans);
//    		trans.startNow();
//    		this.startAnimation(trans);
//        	mode = NONE;
//    		Log.v("touch", "action up");
    		break;
        case MotionEvent.ACTION_POINTER_UP:
//            mode = NONE;
        	if (!multiFinger) {
        		break;
        	}
        	if (event.getActionIndex() == 1) {
        		multiFinger = false;
            	Canvas canvas = sh.lockCanvas();
            	canvas.restore();
            	sh.unlockCanvasAndPost(canvas);
        		getBasePostion(event, true);
        	}
        	
//        	Log.v("p up", event.getActionIndex() + "");
        	
            break;
        case MotionEvent.ACTION_MOVE:

//        	int x1 = 0;
//        	int y1 = 0;
        	if (multiFinger && event.getPointerCount() >= 2) {
            	scale = 1f;
            	if (beforeLenght > 0) {
            		// 执行缩放
            		afterLenght = spacing(event);
            		scale = afterLenght / beforeLenght;
            	}
//            	Log.v("pic move", event.getX(0) + "," + event.getY(0) + "  " + event.getX(1) + "," + event.getY(1));
//            	setDrawingCacheEnabled(true);
//            	measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
//            			MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 
//            	layout(0, 0, getMeasuredWidth(), getMeasuredHeight()); 
//            	buildDrawingCache(true);
//            	boolean bb = willNotCacheDrawing();
//            	boolean cc = isDrawingCacheEnabled();
//            	Bitmap bmp = getDrawingCache(true);
            	Matrix m = new Matrix();
            	m.postScale(scale, scale);

            	int newW = (int) (scale * w0);
            	int newH = (int) (scale * h0);
//            	int xDis = (int) ((newW - w0) * xpos);
//            	int yDis = (int) ((newH - h0) * ypos);
//            	Log.v("draw zoom", "xdis:"+xDis+",ydis:"+yDis+",xpos:"+xpos);
    			float x1 = (event.getX() + event.getX(1)) / 2;
    			float y1 = (event.getY() + event.getY(1)) / 2;
    			int xDis = (int) (x1 - x0);
    			int yDis = (int) (y1 - y0);
            	
////            	int newL = (int) (x0 - x0 * scale);
//            	int newL = (int) (x0 - (x0 - l0) * scale + xDis);
////            	int newT = (int) (y0 - y0 * scale);
////            	int newT = (int) (t0 - (newH - h0) * (y0 - t0) / th);
//            	int newT = (int) (y0 - (y0 - t0) * scale + yDis);
            	

            	
//            	int newL = (int) (l0 - newW * (x0 / w0) + x0);
//            	int newT = (int) (t0 - newH * (y0 / h0) + y0);
            	
//            	int newL = (int) (l0 - newW * (x0 / w0) + x0 + event.getRawX() - rx0);
//            	int newT = (int) (t0 - newH * (y0 / h0) + y0 + event.getRawY() - ry0);
//            	this.layout(newL, newT, newW + newL, newH + newT);
//            	this.layout(l0 - xDis, t0 - yDis, l0 - xDis + newW, t0 - yDis + newH);
//    			this.layout(l0 - xDis, t0 - yDis, l0 - xDis + newW, t0 - yDis + newH);
            	
//            	this.setScaleX(scale);
//            	this.setScaleY(scale);
//            	//            	Bitmap newImg = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
//            	Canvas canvas = sh.lockCanvas();
//            	canvas.drawBitmap(drawUtil.getCacheBitmap(), m, null);
//            	sh.unlockCanvasAndPost(canvas);
//            	this.destroyDrawingCache();
            	

        	} else {
            	int xDis = (int) (event.getX() - x0);
            	int yDis = (int) (event.getY() - y0);
            	this.layout(this.getLeft() + xDis, this.getTop() + yDis, this.getRight() + xDis, this.getBottom() + yDis);
        	}
        	
            break;
        }
        return true;	
	}
	
	private void getBasePostion(MotionEvent event, boolean singlePT) {

		w0 = this.getWidth();
		h0 = this.getHeight();
		l0 = this.getLeft();
		t0 = this.getTop();
		
		if (singlePT) {
			// 单点
			x0 = event.getX();
			y0 = event.getY();
			beforeLenght = 0;
		} else {
			// 多点
			x0 = (event.getX() + event.getX(1)) / 2;
			y0 = (event.getY() + event.getY(1)) / 2;
			xpos = x0 / w0;
			ypos = y0 / h0;
			beforeLenght = spacing(event);
        	Canvas canvas = sh.lockCanvas();
        	canvas.save();
        	canvas.translate(x0, y0);
        	sh.unlockCanvasAndPost(canvas);
		}

//		rx0 = event.getRawX();
//		ry0 = event.getRawY();
	}
	

	
	
	
	
	
	
	
	
	
	
	
	
	
	public MapDisp(Context context) {
		super(context);
		this.setPadding(0, 0, 0, 0);
		Display disp = ((Activity)context).getWindowManager().getDefaultDisplay();
		tw = disp.getWidth();
		th = disp.getHeight();
		ctx = context;
		sh = this.getHolder();
		sh.addCallback(this);
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Canvas canvas = holder.lockCanvas();
		stationInfo = IniParser.getStationInfo(ctx);
		stationInfo.jkxxMap = IniParser.getJKXXList(ctx);
		ss = stationInfo.getStationSummary();
    	drawUtil = new DrawUtil(ctx, ss, 1);
    	// 获得所有控件信息
    	sbList = stationInfo.getCtlList();
    	// 绘制各个控件
    	drawUtil.drawNet();
    	drawUtil.drawControls(stationInfo.getCtlList());
    	cacheImage = drawUtil.getCacheBitmap();
    	canvas.drawBitmap(cacheImage, 0, 0, null);
    	holder.unlockCanvasAndPost(canvas);
    	holder.lockCanvas(new Rect(0, 0, 0, 0));
    	holder.unlockCanvasAndPost(canvas);
	}

//	private final Timer timer = new Timer();
//	private TimerTask task;
	Handler handler;
	
	public void drawChanged(int[] changeArray) {
		
		Switcher sw = null;
		Switcher st = null;
//		int cnt = 0;
		// 第一次循环，将所有低电平开关状态清零
		for (int x : changeArray) {
			String key = stationInfo.jkxxMap.get(Math.abs(x));
			if (key == null) {
				continue;
			}
			
			sw = stationInfo.switcherMap.get(key);
			if (sw == null) {
				continue;
			}
			
//			for (Integer swIdx : sw.ctlIdxList) {
			
			if (x < 0) {
				sw.status = 0;
//				stationInfo.switcherMap.put(key, sw);
//				if (sw.type.equals(Const.EQUI_XHJ)) {
//					Log.v("draw lamp", "low at : " + key + ", color index:" + sw.colorIndex);
//				}
			} else {
//				if (sw.type.equals(Const.EQUI_XHJ)) {
//					Log.v("draw lamp", "high at : " + key + ", color index:" + sw.colorIndex);
//				}
				for (Integer idx : sw.ctlIdxList) {
					EquipmentInfo ei = stationInfo.ctlList.get(idx);
					if (ei.getSwMap() == null || ei.getSwMap().get(key) == null) {
						Log.v("data error", "sb index:"+idx+",sb type:"+ei.getName());
					}
					int swIdx = 0;
					if (ei.getSwMap().keySet().contains(key)) {
						swIdx = ei.getSwMap().get(key);
					} else {
						if (((EquipDC) ei).getSwPosList().get(0).equals(key)) {
							swIdx = Const.SW_DC_CINDEX_FIX;
						} else {
							swIdx = Const.SW_DC_CINDEX_OPP;
						}
					}
					if (ei.getName().equals(Const.EQUI_DC) 
							&& (swIdx == Const.SW_DC_CINDEX_FIX 
							|| swIdx == Const.SW_DC_CINDEX_OPP)) {
						EquipDC edc = (EquipDC) ei;
						// 道岔定位与反位开关量重置
						if (swIdx == Const.SW_DC_CINDEX_FIX) {
							// 定位高
							edc.setStatus(0);
						} else {
							edc.setStatus(1);
						}
						ArrayList<String> swPosList = edc.getSwPosList();
						if (swPosList != null) {
							for (String s : swPosList) {
								st = stationInfo.switcherMap.get(s);
								st.status = 0;
							}
						}
					} else if (ei.getName().equals(Const.EQUI_XHJ) 
							&& swIdx == Const.SW_XHJ_CINDEX_YELLOW
							&& ((EquipXHJ) ei).lampCount == 2) {
						// 信号机黄灯亮时灭绿灯外的另一个灯位
						Iterator<Entry<String, Integer>> itsw = ei.getSwMap().entrySet().iterator();
						while (itsw.hasNext()) {
							Entry<String, Integer> entry = itsw.next();
							String keyTmp = entry.getKey();
							st = stationInfo.switcherMap.get(keyTmp);
							if (entry.getValue() != Const.SW_XHJ_CINDEX_GREEN) {
								st.status = 0;
							}
						}
					} else {
						// 开关对应控件的所有开关量状态清零
						Iterator<Entry<String, Integer>> itsw = ei.getSwMap().entrySet().iterator();
						while (itsw.hasNext()) {
							Entry<String, Integer> entry = itsw.next();
							String keyTmp = entry.getKey();
							st = stationInfo.switcherMap.get(keyTmp);
							if (entry.getValue() != Const.SW_XHJ_CINDEX_GREEN) {
								st.status = 0;
							}
						}
					}
				}
				sw.status = 1;
			}
		}
		
		// 重新计算所有逻辑开关量的值
		// TODO:仅修改改变了的开关量的逻辑开关值
		String t = "31";
		String tp1 = t + "-QB";
		String tp2 = t + "-QH";
		String tp3 = "";
		Iterator<Entry<String, LogicSwitcher>> lsLoop = stationInfo.lsMap.entrySet().iterator();
		while (lsLoop.hasNext()) {
			Entry<String, LogicSwitcher> entry = lsLoop.next();
			LogicSwitcher ls = entry.getValue();

			int ret = getSwitcherStatus(entry.getKey(), stationInfo);
			
			if (entry.getKey().equals(tp1) || entry.getKey().equals(tp2)) {
				if (ret == 1) {
					Log.v("md drawChange", "logic switcher "+ entry.getKey()+":1");
					tp3 = entry.getKey();
				}
			}
			
			ls.status = ret;
			Switcher tmpSw = stationInfo.switcherMap.get(entry.getKey());
			tmpSw.status = ret;
		}
		
		// 第二次循环，遍历开关列表，将所有高电平开关画到图上
		Canvas canvas = sh.lockCanvas();
		canvas.drawBitmap(cacheImage, 0, 0, null);
		
		
		for (EquipmentInfo ep : stationInfo.ctlList) {
			
			if (ep.getSwMap() == null) {
				continue;
			}
			
			if (ep.getName().equals(Const.EQUI_DC)) {
				EquipDC dc = (EquipDC) ep;
				int color = Const.COLOR_DEACTIVE;
				
				Iterator<Entry<String, Integer>> itsw = dc.getSwMap().entrySet().iterator();
				while (itsw.hasNext()) {
					Entry<String, Integer> entry = itsw.next();
					String keyTmp = entry.getKey();
					Switcher swTmp = stationInfo.switcherMap.get(keyTmp);
					if (swTmp.status == 1) {
						if (entry.getValue() == Const.SW_DC_CINDEX_BEF_RED) {
							// 红白同高时优先显示红灯
							color = getDrawColor(ep.getName(), entry.getValue());
							break;
						} else if (entry.getValue() == Const.SW_DC_CINDEX_BEF_WHITE) {
							color = getDrawColor(ep.getName(), entry.getValue());
						}
//						Log.v("draw change", "dc sw:"+keyTmp+"");
					}
				}
				
				drawUtil.drawSbDC(dc, color, canvas);
			} else if (ep.getName().equals(Const.EQUI_WCQD)) {
				Iterator<Entry<String, Integer>> itsw = ep.getSwMap().entrySet().iterator();
				int color = Const.COLOR_DEACTIVE;
				while (itsw.hasNext()) {
					Entry<String, Integer> entry = itsw.next();
					String keyTmp = entry.getKey();
					Switcher swTmp = stationInfo.switcherMap.get(keyTmp);
					if (swTmp.status == 1) {
						if (entry.getValue() == Const.SW_WCQD_CINDEX_RED) {
							color = Color.RED;
							break;
						} else {
							color = Color.WHITE;
						}
					}
				}
//				color = getDrawColor(ep.getName(), entry.getValue());
				drawUtil.drawSbWCQD(ep, color, canvas);
			} else {
				Iterator<Entry<String, Integer>> itsw = ep.getSwMap().entrySet().iterator();
				while (itsw.hasNext()) {
					Entry<String, Integer> entry = itsw.next();
					String keyTmp = entry.getKey();
					
					
					
					
					
					Switcher swTmp = stationInfo.switcherMap.get(keyTmp);
					if (ep.getDisp().equals("2/4") || keyTmp.equals(tp3)) {
						Log.v("md drawchange", "before draw sw : " + tp3 + ",status:" + swTmp.status);
					}
					if (swTmp.status == 1) {
						int color = 0;
						if (ep.getName().equals(Const.EQUI_XHJ)) {
		//					Log.v("draw lamp", "High at : " + entry.getKey() + ", color index:" + st.colorIndex);
							color = getDrawColor(ep.getName(), entry.getValue());
							EquipXHJ ex = (EquipXHJ) ep;
							if (entry.getValue() == Const.SW_XHJ_CINDEX_YELLOW && ex.lampCount == 2) {
								drawUtil.drawSbXHJLamp2(ex, color, canvas);
							} else {
								drawUtil.drawSbXHJLamp1(ex, color, canvas);
							}
						} else if (ep.getName().equals(Const.EQUI_DHAN)) {
							if (ep.getType() != Const.TYPE_BTN_DCBS) {
								color = getDrawColor(ep.getName(), entry.getValue());
								drawUtil.drawSbDHANLamp(ep, color, canvas);
							} else {
								if (entry.getValue() == Const.TYPE_BTN_DC_FIX) {
									Log.v("draw dcbs", ep.getDisp() + " : green");
									color = Color.GREEN;
									drawUtil.drawSbDHANLamp(ep, color, canvas);
								} else if (entry.getValue() == Const.TYPE_BTN_DC_OPP) {
									Log.v("draw dcbs", ep.getDisp() + " : yellow");
									color = Color.YELLOW;
									drawUtil.drawSbDHANLamp(ep, color, canvas);
								}
							}
							
		//					Log.v("md", "draw wcqd with color:"+color);
						}
					}
				}
			}
		}

		sh.unlockCanvasAndPost(canvas);
	}
	
	public void showLog() {
		for (int idx : stationInfo.dcIdxList) {
			EquipDC dc = (EquipDC) stationInfo.ctlList.get(idx);
			if (dc.getDisp().equals("16")) {
				StringBuffer lg = new StringBuffer();
				lg.append("status:").append(dc.getStatus());
				for (String s : dc.getSwPosList()) {
					lg.append(",psw:").append(s).append(":").append(stationInfo.switcherMap.get(s).status);
				}
				Iterator<Entry<String, Integer>> itsw = dc.getSwMap().entrySet().iterator();
				while (itsw.hasNext()) {
					Entry<String, Integer> entry = itsw.next();
					String keyTmp = entry.getKey();
					Switcher sw = stationInfo.switcherMap.get(keyTmp);
					lg.append(",csw:").append(keyTmp).append(":").append(sw.status);
				}
//				for (String s : dc.getSwList()) {
//					Switcher sw = stationInfo.switcherMap.get(s);
//					lg.append(",csw:").append(s).append(":").append(sw.status);
//				}
				Log.v("md showlog", lg.toString());
			}
		}
		Log.v("md showlog", "switch status:"+ getSwitcherStatus("23-FH", stationInfo)+"");
	}
	
	private int getSwitcherStatus(String swName, StationInfo si) {
		
		LogicSwitcher ls = si.lsMap.get(swName);
		if (ls == null) {
			// 非逻辑开关量，直接从开关map中取值
			return si.switcherMap.get(swName).status;
		} else {
			// 逻辑开关量，要计算
			int v = getSwitcherStatus(ls.swNames[0], si);
			int ret = 0;
			for (int i = 1; i < ls.swCount; i ++) {
				int v1 = getSwitcherStatus(ls.swNames[i], si);
				ret = LogicSwitcher.getSwValue(v, v1, ls.method);
				v = ret;
			}
			return ret;
		}
	}
	
	private int getDrawColor(String ctlType, int index) {
		if (ctlType.equals(Const.EQUI_XHJ)) {
			switch (index) {
			case Const.SW_XHJ_CINDEX_BLUE:
				return Color.BLUE;
			case Const.SW_XHJ_CINDEX_GREEN:
				return Color.GREEN;
			case Const.SW_XHJ_CINDEX_GREEN2:
				return Color.GREEN;
			case Const.SW_XHJ_CINDEX_RED:
				return Color.RED;
			case Const.SW_XHJ_CINDEX_WHITE:
				return Color.WHITE;
			case Const.SW_XHJ_CINDEX_YELLOW:
				return Color.YELLOW;
			case Const.SW_XHJ_CINDEX_YELLOW2:
				return Color.YELLOW;
			}
		} else if (ctlType.equals(Const.EQUI_DHAN)) {
			switch (index) {
			case Const.SW_DHAN_CINDEX_BLUE:
				return Color.BLUE;
			case Const.SW_DHAN_CINDEX_GREEN:
				return Color.GREEN;
			case Const.SW_DHAN_CINDEX_RED:
				return Color.RED;
			case Const.SW_DHAN_CINDEX_SIG:
				return Color.CYAN;
			case Const.SW_DHAN_CINDEX_WHITE:
				return Color.WHITE;
			case Const.SW_DHAN_CINDEX_YELLOW:
				return Color.YELLOW;
			}
		} else if (ctlType.equals(Const.EQUI_WCQD)) {
			switch (index) {
			case Const.SW_WCQD_CINDEX_RED:
				return Color.RED;
			case Const.SW_WCQD_CINDEX_WHITE:
				return Color.WHITE;
			}
		} else if (ctlType.equals(Const.EQUI_DC)) {
			switch (index) {
			case Const.SW_DC_CINDEX_AF_FIX_RED:
			case Const.SW_DC_CINDEX_AF_OPP_RED:
			case Const.SW_DC_CINDEX_BEF_RED:
				return Color.RED;
			case Const.SW_DC_CINDEX_AF_FIX_WHITE:
			case Const.SW_DC_CINDEX_AF_OPP_WHITE:
			case Const.SW_DC_CINDEX_BEF_WHITE:
				return Color.WHITE;
			case Const.SW_DC_CINDEX_FIX:
			case Const.SW_DC_CINDEX_OPP:
				return Color.GRAY;
			}
		}
		return 0;
	}

	public void drawSome() {
//		
//		task = new TimerTask() {
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				Message message = new Message();
//				message.what = 1;
//				handler.sendMessage(message);
//			}
//		};
//
//		timer.scheduleAtFixedRate(task, 1000, 1000);
	}

	public void Zoom(float scale) {
//		timer.cancel();
//		Matrix m = new Matrix();
//		m.postScale(scale, scale);
//		Bitmap newImg = Bitmap.createBitmap(cacheImage, 0, 0, cacheImage.getWidth(), cacheImage.getHeight(), m, true);
//		Canvas canvas = sh.lockCanvas();
//		canvas.drawBitmap(newImg, 0, 0, null);
//		sh.unlockCanvasAndPost(canvas);
//		cacheImage = newImg;
//		DrawUtil drawUtil = new DrawUtil(ctx, ss, scale);
//		drawUtil.drawControls(sInfo.getCtlList());
//		canvas.drawBitmap(drawUtil.getCacheBitmap(), 0, 0, null);
//		sh.unlockCanvasAndPost(canvas);
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		
	}
	
	public void setStationInitData(int[] data) {
		Log.v("set station", data[0] + "," + data[1] + "," + data[2]);
		int iStart = 0;
		int len = data.length;
		if (data[0] == 0x01 && data[1] == 0x22) {
			iStart = 4;
			len -= 7;
		}
		for (int i = iStart; i < len; i++) {
			int tmp = data[i + iStart];
			for (int j = 0; j < 8; j++) {
//				int key = i * 8 + (8 - j);
//				int value = tmp & 0x1;
//				Log.v("initData", "key:"+key+",value:"+value);
				String key = stationInfo.jkxxMap.get((i - iStart) * 8 + j + 1);
				int x = (i - iStart) * 8 + j + 1;

				Switcher sw = stationInfo.switcherMap.get(key);
				if (sw != null) {
					sw.status = (tmp >>> j) & 0x1;
					// 开关1-8取第一字节的第8-1位
					if (x >= 968 && x <= 969) {
						Log.v("initdata.......", x + ":" + sw.status  + ", data:" + tmp);
					}
					
//					stationInfo.switcherMap.put(key, sw);
//					if (sw.type.equals(Const.EQUI_DC)) {
//						if (sw.status == 1 && 
//								(sw.colorIndex == Const.SW_DC_CINDEX_FIX || sw.colorIndex == Const.SW_DC_CINDEX_OPP)) {
//							for (Integer idx : sw.ctlIdxList) {
//								EquipDC ei = (EquipDC) stationInfo.ctlList.get(idx);
//								// 道岔定位与反位
//								ei.setStatus(sw.colorIndex);
//							}
//						}
//					}
				} else {
					int ii = 0;
				}
//				stationInfo.jkxxStatus.put(i * 8 + (8 - j), tmp & 0x1);
//				tmp = tmp >>> 1;
			}
		}
		
		for (Integer idx : stationInfo.dcIdxList) {
			// 道岔的定位与反位
			EquipDC dc = (EquipDC) stationInfo.ctlList.get(idx);
			String swName = dc.getSwPosList().get(1);
			Switcher sw = stationInfo.switcherMap.get(swName);
			dc.setStatus(sw.status == 1 ? 1 : 0);
		}
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//		setMeasuredDimension(measuredHeight, measuredWidth);
	}


}
